# -*- coding: UTF-8 -*-
# Author: Damon(wuud1)
# CreateDate: 
# Message:  # 清洗数据的时候没有psort
from MysqlTools import MysqlTools
import json


class UpdatePsort:

    def __init__(self, **kwargs):
        self.db = MysqlTools(db_config=kwargs.get("db_config"), type='dict')
        self.p_table = kwargs.get("p_table")

    def run(self):
        sql = '''select distinct `id`,`cid`,`num`,`mid` from `{}`'''.format(self.p_table)
        data = self.db.select_all(sql)
        _dict = {}
        for info in data:
            id=info.get("id")
            cid=info.get("cid")
            num=info.get("num")
            mid=info.get("mid")
            key = cid+'_'+num+'_'+mid
            if key not in _dict:
                _dict[key] = [id]
            else:
                _dict[key].append(id)
        for k, v in _dict.items():
            info_l = k.split("_")
            # cid=info_l[0]
            # num=info_l[1]
            # mid=info_l[2]
            id_l = v
            id_l.sort()
            psort = 1
            for id in id_l:
                up_sql = '''update `{}` set `psort`={} where `id`="{}";'''.format(self.p_table, psort, id)
                self.db.execute_sql(up_sql)
                psort += 1
        self.db.commit_sql()
        print('end...')


    def up_date(self):

        def format_date(str):
            if str.strip() == '':
                return str.strip()
            date_l = str.split("/")
            Y = date_l[0]
            M = date_l[1]
            d = date_l[2]
            f_date = '%d%02d%02d' % (int(Y), int(M), int(d))
            return f_date

        # 取出所有id,extra_info
        sql = '''select `id`,`extra_info` from `{}`;'''.format(self.p_table)
        data = self.db.select_all(sql)
        for info in data:
            id=info.get("id")
            extra_info=json.loads(info.get("extra_info"))
            s_time = extra_info.get("s_time")
            e_time = extra_info.get("e_time")
            s_time = s_time.split(" ")[0] if s_time.strip() else ''
            e_time = e_time.split(" ")[0] if e_time.strip() else ''
            new_time = format_date(s_time)+'-'+format_date(e_time)
            up_sql = '''update `{}` set `condition`="{}" where `id`="{}"'''.format(self.p_table, new_time, id)
            self.db.execute_sql(up_sql)
        self.db.commit_sql()

if __name__ == '__main__':
    db_config = dict(
        host="127.0.0.1",
        port=3306,
        user="root",
        passwd="123456",
        db="JAC",
        charset="utf8",
    )
    p_table = 'cars_part_num'
    tools = UpdatePsort(db_config=db_config, p_table=p_table)
    # tools.run()
    tools.up_date()